package cn.iocoder.yudao.module.design.service.pic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.design.controller.admin.pic.vo.PicCreateReqVO;
import cn.iocoder.yudao.module.design.controller.admin.pic.vo.PicExportReqVO;
import cn.iocoder.yudao.module.design.controller.admin.pic.vo.PicPageReqVO;
import cn.iocoder.yudao.module.design.controller.admin.pic.vo.PicUpdateReqVO;
import cn.iocoder.yudao.module.design.convert.pic.PicConvert;
import cn.iocoder.yudao.module.design.dal.dataobject.pic.PicDO;
import cn.iocoder.yudao.module.design.dal.mysql.pic.PicMapper;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FileRespVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.design.enums.ErrorCodeConstants.PIC_NOT_EXISTS;

/**
 * 图片 Service 实现类
 *
 * @author czw
 */
@Service
@Validated
public class PicServiceImpl implements PicService {

    @Resource
    private PicMapper picMapper;

    @Override
    public Long createPic(PicCreateReqVO createReqVO) {
        // 插入
        PicDO pic = PicConvert.INSTANCE.convert(createReqVO);
        picMapper.insert(pic);
        // 返回
        return pic.getId();
    }

    @Override
    public void updatePic(PicUpdateReqVO updateReqVO) {
        // 校验存在
        this.validatePicExists(updateReqVO.getId());
        // 更新
        PicDO updateObj = PicConvert.INSTANCE.convert(updateReqVO);
        picMapper.updateById(updateObj);
    }

    @Override
    public void deletePic(Long id) {
        // 校验存在
        this.validatePicExists(id);
        // 删除
        picMapper.deleteById(id);
    }

    private void validatePicExists(Long id) {
        if (picMapper.selectById(id) == null) {
            throw exception(PIC_NOT_EXISTS);
        }
    }

    @Override
    public List<Map> getPicListByIds(String ids)
    {
        return picMapper.getPicsByHouseIds(ids);
    }
    @Override
    public PicDO getPic(Long id) {
        return picMapper.selectById(id);
    }

    @Override
    public List<PicDO> getPicList(Collection<Long> ids) {
        return picMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<PicDO> getPicPage(PicPageReqVO pageReqVO) {
        return picMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PicDO> getPicList(PicExportReqVO exportReqVO) {
        return picMapper.selectList(exportReqVO);
    }



    @Transactional(rollbackFor = {})
    public void savePicData(PicDO picDo,   List<FileRespVO> fileRespVOList ){
        // 将存量图片置位失效
        updatePicDOStatus(picDo);
        savePicDataAll(picDo,fileRespVOList);
    }

    /**
     * 保存图片
     * @param picDo
     * @param fileRespVOList
     */
    @Override
    public void savePicDataAll(PicDO picDo, List<FileRespVO> fileRespVOList) {
        if(CollUtil.isNotEmpty(fileRespVOList)){


            // 修改或新增 图片
            PicDO picDoItem = null;
            QueryWrapper query = null;
            for(FileRespVO vo : fileRespVOList){
                picDoItem = new PicDO();
                picDoItem.setId(vo.getId());
                picDoItem.setHouseId(picDo.getHouseId());
                picDoItem.setFlowId(picDo.getFlowId());
                picDoItem.setNodeId(picDo.getNodeId());
                picDoItem.setItemId(picDo.getItemId());
                picDoItem.setUploadType( picDo.getUploadType());
                picDoItem.setSourceType(picDo.getSourceType());
                picDoItem.setName(vo.getName());
                picDoItem.setUrl(vo.getUrl());

                picDoItem.setDeleted(false);
                picDoItem.setSize(vo.getSize());


                picDo.setId(vo.getId());
                // 失效的 图片
                picDo.setStatus("1");
                Long count = getPicDataCount(picDo);
                picDoItem.setStatus("0");

                if(count >0){
                    picMapper.updateById(picDoItem);
                }else{
                    picDoItem.setCreator(SecurityFrameworkUtils.getLoginUserId().toString());
                    picMapper.insert(picDoItem);

                }

            }
        }
    }


    @Transactional(rollbackFor = {})
    public void updatePicDOStatus( PicDO picDo){
        PicDO picDoUp = new PicDO();
        picDoUp.setDeleted(true);
        picDoUp.setStatus("1");
        QueryWrapper upWhere = new QueryWrapper();

        upWhere.eq("house_id",picDo.getHouseId());
        if(ObjectUtil.isNotNull(picDo.getFlowId())){
            upWhere.eq("flow_id",picDo.getFlowId());
        }else{
            upWhere.isNull("flow_id" );
        }

        if(ObjectUtil.isNotNull(picDo.getNodeId())){
            upWhere.eq("node_id",picDo.getNodeId());
        }else{
            upWhere.isNull("node_id" );
        }

        if(ObjectUtil.isNotNull(picDo.getItemId())){
            upWhere.eq("item_id",picDo.getItemId());
        }else{
            upWhere.isNull("item_id" );
        }


        upWhere.eq("upload_type",picDo.getUploadType()   );
        upWhere.eq("source_type",picDo.getSourceType());
        picMapper.update(picDoUp,upWhere);
    }



    public List<PicDO> getPicData(PicDO vo){

        QueryWrapper<PicDO> queryWrapper = new QueryWrapper<PicDO>();
        if(!Objects.isNull(vo.getId())){

            queryWrapper.eq("id",vo.getId());
        }

        queryWrapper.eq("house_id",vo.getHouseId());
        if(Objects.isNull(vo.getFlowId())){
            queryWrapper.isNull("flow_id");
        }else{
            queryWrapper.eq("flow_id",vo.getFlowId());
        }

        if(Objects.isNull(vo.getNodeId())){
            queryWrapper.isNull("node_id");
        }else{
            queryWrapper.eq("node_id",vo.getNodeId());
        }

        if(Objects.isNull(vo.getItemId())){
            queryWrapper.isNull("item_id");
        }else{
            queryWrapper.eq("item_id",vo.getItemId());
        }

        queryWrapper.eq("status","0");
        if(!Objects.isNull(vo.getSourceType())){
            queryWrapper.eq("source_type",vo.getSourceType());
        }

        queryWrapper.eq("upload_type",vo.getUploadType());
        queryWrapper.orderByAsc("id");
        List<PicDO> list = picMapper.selectList(queryWrapper);
        return list;
    }

    public Long getPicDataCount(PicDO vo){

        QueryWrapper<PicDO> queryWrapper = new QueryWrapper<PicDO>();
        queryWrapper.eq("id",vo.getId());

        queryWrapper.eq("house_id",vo.getHouseId());
        if(Objects.isNull(vo.getFlowId())){
            queryWrapper.isNull("flow_id");
        }else{
            queryWrapper.eq("flow_id",vo.getFlowId());
        }

        if(Objects.isNull(vo.getNodeId())){
            queryWrapper.isNull("node_id");
        }else{
            queryWrapper.eq("node_id",vo.getNodeId());
        }

        if(Objects.isNull(vo.getItemId())){
            queryWrapper.isNull("item_id");
        }else{
            queryWrapper.eq("item_id",vo.getItemId());
        }

        if(!Objects.isNull(vo.getStatus())){
            queryWrapper.eq("status",vo.getStatus());
        }else{
            queryWrapper.eq("status","0");
        }
//
        queryWrapper.eq("source_type",vo.getSourceType());
        queryWrapper.eq("upload_type",vo.getUploadType());
        Long count = picMapper.selectCount(queryWrapper);
        return count;
    }

    @Override
    public List<PicDO> getPicData(Long houseId, List<String> sourceTypeList) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("house_id",houseId);
        queryWrapper.in("source_type",sourceTypeList);
        queryWrapper.eq("status","0");

        return picMapper.selectList(queryWrapper);
    }
}
